package com.jxw.cloudpen.web.microsoft;

/**
 * @author ligang
 * @create 2025/4/16 14:51
 */
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.*;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class SpeechSynthesis {
    // This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
//    private static String speechKey = System.getenv("SPEECH_KEY");
//    private static String speechRegion = System.getenv("SPEECH_REGION");

    private static String speechKey = "bc9a5386c73947948aaaedf6d115f87c";
    private static String speechRegion = "southeastasia";



    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SpeechConfig speechConfig = SpeechConfig.fromSubscription(speechKey, speechRegion);

        speechConfig.setSpeechSynthesisVoiceName("en-US-AvaMultilingualNeural");

        AudioConfig audioConfig = AudioConfig.fromWavFileOutput("D://file1.wav");


        SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(speechConfig,audioConfig);

        // Get text from the console and synthesize to the default speaker.
        System.out.println("Enter some text that you want to speak >");
//        String text = new Scanner(System.in).nextLine();
//        if (text.isEmpty())
//        {
//            return;
//        }

        String text="Enter some text that you want to speak";

        speechSynthesizer.SpeakText("I'm excited to try text to speech");

        SpeechSynthesisResult speechSynthesisResult = speechSynthesizer.SpeakTextAsync(text).get();
        if (speechSynthesisResult.getReason() == ResultReason.SynthesizingAudioCompleted) {
            System.out.println("Speech synthesized to speaker for text [" + text + "]");
        }
        else if (speechSynthesisResult.getReason() == ResultReason.Canceled) {
            SpeechSynthesisCancellationDetails cancellation = SpeechSynthesisCancellationDetails.fromResult(speechSynthesisResult);
            System.out.println("CANCELED: Reason=" + cancellation.getReason());

            if (cancellation.getReason() == CancellationReason.Error) {
                System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
                System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
                System.out.println("CANCELED: Did you set the speech resource key and region values?");
            }
        }

        System.exit(0);
    }
}